package com.bianmaba.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Base64编码工具类
 *
 * @author cWX183898
 */
public final class Base64Util {
    public static final Log LOG = LogFactory.getLog(MD5Utils.class);

    private static final byte[] ENCODING_TABLE = new byte[]{(byte) 'A',
            (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
            (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
            (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
            (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
            (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
            (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
            (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
            (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o',
            (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
            (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y',
            (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
            (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8',
            (byte) '9', (byte) '+', (byte) '/'};

    private static final byte[] DECODING_TABLE;

    static {
        DECODING_TABLE = new byte[128];
        for (int i = 0; i < 128; i++) {
            DECODING_TABLE[i] = (byte) -1;
        }
        for (int i = 'A'; i <= 'Z'; i++) {
            DECODING_TABLE[i] = (byte) (i - 'A');
        }
        for (int i = 'a'; i <= 'z'; i++) {
            DECODING_TABLE[i] = (byte) (i - 'a' + 26);
        }
        for (int i = '0'; i <= '9'; i++) {
            DECODING_TABLE[i] = (byte) (i - '0' + 52);
        }
        DECODING_TABLE['+'] = 62;
        DECODING_TABLE['/'] = 63;
    }

    private Base64Util() {
    }

    /**
     * 将字节数组进行编码
     *
     * @param data   源数据
     * @param offset 起始偏移
     * @return 编码后的字节数组
     */
    public static byte[] encode(byte[] data, int offset) {
        byte[] bytes;
        int realCount = data.length - offset;
        int modulus = realCount % 3;
        if (modulus == 0) {
            bytes = new byte[(4 * realCount) / 3];
        } else {
            bytes = new byte[4 * ((realCount / 3) + 1)];
        }
        int dataLength = (data.length - modulus);
        int a1;
        int a2;
        int a3;

        List<Byte> list = new ArrayList<Byte>(0);
        int i = offset;
        int j = 0;
        for (; i < dataLength; i += 3, j += 4) {
            a1 = data[i] & 0xff;
            a2 = data[i + 1] & 0xff;
            a3 = data[i + 2] & 0xff;
            list.add(ENCODING_TABLE[(a1 >>> 2) & 0x3f]);
            list.add(ENCODING_TABLE[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
            list.add(ENCODING_TABLE[((a2 << 2) | (a3 >>> 6)) & 0x3f]);
            list.add(ENCODING_TABLE[a3 & 0x3f]);
        }
        int size = list.size();
        for (int k = 0; k < size; k++) {
            bytes[k] = list.get(k);
        }
        int b1;
        int b2;
        int b3;
        int d1;
        int d2;
        switch (modulus) {
            case 0: /* nothing left to do */
                break;
            case 1:
                d1 = data[data.length - 1] & 0xff;
                b1 = (d1 >>> 2) & 0x3f;
                b2 = (d1 << 4) & 0x3f;
                bytes[bytes.length - 4] = ENCODING_TABLE[b1];
                bytes[bytes.length - 3] = ENCODING_TABLE[b2];
                bytes[bytes.length - 2] = (byte) '=';
                bytes[bytes.length - 1] = (byte) '=';
                break;
            case 2:
                d1 = data[data.length - 2] & 0xff;
                d2 = data[data.length - 1] & 0xff;
                b1 = (d1 >>> 2) & 0x3f;
                b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
                b3 = (d2 << 2) & 0x3f;
                bytes[bytes.length - 4] = ENCODING_TABLE[b1];
                bytes[bytes.length - 3] = ENCODING_TABLE[b2];
                bytes[bytes.length - 2] = ENCODING_TABLE[b3];
                bytes[bytes.length - 1] = (byte) '=';
                break;
            default:
        }
        return bytes;
    }

    /**
     * 将字节数组进行解码码
     *
     * @param data 源数据
     * @param data
     * @return
     */
    public static byte[] decode(byte[] data) {
        byte[] bytes;
        byte b1;
        byte b2;
        byte b3;
        byte b4;
        data = discardNonBase64Bytes(data);
        int dataLengh = data.length;
        if (data[dataLengh - 2] == '=') {
            bytes = new byte[(((dataLengh / 4) - 1) * 3) + 1];
        } else if (data[dataLengh - 1] == '=') {
            bytes = new byte[(((dataLengh / 4) - 1) * 3) + 2];
        } else {
            bytes = new byte[((dataLengh / 4) * 3)];
        }
        int i = 0;
        int j = 0;
        for (; i < (dataLengh - 4); i += 4, j += 3) {
            b1 = DECODING_TABLE[data[i]];
            b2 = DECODING_TABLE[data[i + 1]];
            b3 = DECODING_TABLE[data[i + 2]];
            b4 = DECODING_TABLE[data[i + 3]];
            bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[j + 2] = (byte) ((b3 << 6) | b4);
        }
        if (data[dataLengh - 2] == '=') {
            b1 = DECODING_TABLE[data[dataLengh - 4]];
            b2 = DECODING_TABLE[data[dataLengh - 3]];
            bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
        } else if (data[dataLengh - 1] == '=') {
            b1 = DECODING_TABLE[data[dataLengh - 4]];
            b2 = DECODING_TABLE[data[dataLengh - 3]];
            b3 = DECODING_TABLE[data[dataLengh - 2]];
            bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
        } else {
            b1 = DECODING_TABLE[data[dataLengh - 4]];
            b2 = DECODING_TABLE[data[dataLengh - 3]];
            b3 = DECODING_TABLE[data[dataLengh - 2]];
            b4 = DECODING_TABLE[data[dataLengh - 1]];
            bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
        }
        return bytes;
    }

    /**
     * 对字符串进行编码
     *
     * @param data 源字符串
     * @return 编码后的字节数组
     */
    public static byte[] decode(String data) {
        byte[] bytes;
        byte b1;
        byte b2;
        byte b3;
        byte b4;
        data = discardNonBase64Chars(data);
        int dataLength = data.length();
        if (data.charAt(dataLength - 2) == '=') {
            bytes = new byte[(((dataLength / 4) - 1) * 3) + 1];
        } else if (data.charAt(dataLength - 1) == '=') {
            bytes = new byte[(((dataLength / 4) - 1) * 3) + 2];
        } else {
            bytes = new byte[((dataLength / 4) * 3)];
        }
        int i = 0;
        int j = 0;
        for (; i < (dataLength - 4); i += 4, j += 3) {
            b1 = DECODING_TABLE[data.charAt(i)];
            b2 = DECODING_TABLE[data.charAt(i + 1)];
            b3 = DECODING_TABLE[data.charAt(i + 2)];
            b4 = DECODING_TABLE[data.charAt(i + 3)];
            bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[j + 2] = (byte) ((b3 << 6) | b4);
        }
        if (data.charAt(dataLength - 2) == '=') {
            b1 = DECODING_TABLE[data.charAt(dataLength - 4)];
            b2 = DECODING_TABLE[data.charAt(dataLength - 3)];
            bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
        } else if (data.charAt(dataLength - 1) == '=') {
            b1 = DECODING_TABLE[data.charAt(dataLength - 4)];
            b2 = DECODING_TABLE[data.charAt(dataLength - 3)];
            b3 = DECODING_TABLE[data.charAt(dataLength - 2)];
            bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
        } else {
            b1 = DECODING_TABLE[data.charAt(dataLength - 4)];
            b2 = DECODING_TABLE[data.charAt(dataLength - 3)];
            b3 = DECODING_TABLE[data.charAt(dataLength - 2)];
            b4 = DECODING_TABLE[data.charAt(dataLength - 1)];
            bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
        }
        return bytes;
    }

    private static byte[] discardNonBase64Bytes(byte[] data) {
        List<Byte> list = new ArrayList<Byte>(0);
        for (int i = 0; i < data.length; i++) {
            if (isValidBase64Byte(data[i])) {
                list.add(data[i]);
            }
        }
        byte[] newData = new byte[list.size()];
        int size = list.size();
        for (int i = 0; i < size; i++) {
            newData[i] = list.get(i);
        }
        return newData;
    }

    private static String discardNonBase64Chars(String data) {
        StringBuffer sb = new StringBuffer();
        int length = data.length();
        for (int i = 0; i < length; i++) {
            if (isValidBase64Byte((byte) (data.charAt(i)))) {
                sb.append(data.charAt(i));
            }
        }
        return sb.toString();
    }

    private static boolean isValidBase64Byte(byte b) {
        if (b == '=') {
            return true;
        } else if ((b < 0) || (b >= 128)) {
            return false;
        } else if (DECODING_TABLE[b] == -1) {
            return false;
        }
        return true;
    }

    /**
     * 将指定字符串进行Base64编码，可以指定源字符串字符编码
     *
     * @param data    源数据
     * @param charset 源字符编码
     * @return 编码后的字符串
     */
    public static String encode(String data, String charset) {
        try {
            if (data == null || data.length() == 0) {
                return data;
            }
            int offset = 0;
            byte[] result = encode(data.getBytes(charset), offset);
            return new String(result, charset);
        } catch (Exception e) {
            LOG.error("编码出现异常", e);
        }
        return null;
    }

    /**
     * 将指定字符串进行Base64解码，可以返回字符串字符编码
     *
     * @param data    经过编码的源数据
     * @param charset 返回字符串字符编码
     * @return 解码后的字符串
     */
    public static String decode(String data, String charset) {
        try {
            if (data == null || data.length() == 0) {
                return data;
            }
            return new String(Base64Util.decode(data), charset);
        } catch (Exception e) {
            LOG.error("解码码出现异常", e);
        }
        return null;
    }
}